﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using Lucene.Net.Index;
using Lucene.Net.Store;
using System.IO;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Search;

namespace WinFormStudy
{
    public partial class Form_Lucene : Form
    {
        public Form_Lucene()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;//这一行是关键
        }
        Thread t = null;
        private void button1_Click(object sender, EventArgs e)
        {
            DBAccess._connectionString = tbConStr.Text.Trim();

            t = new Thread(DoProcess);
            t.Start();
        }
        private void DoProcess(object obj)
        {
            string sql = "select * from " + tbTable.Text.Trim() + " where ID>239591";
            DataTable dt = DBAccess.ExecuteDataTable(sql);
            lbAll.Text = dt.Rows.Count.ToString();
            int hasDo = 0;
            
            string segPath = tbIndexPath.Text.Trim();

            IndexWriter writer = null;
            FSDirectory directory = null;
            StandardAnalyzer analyzer = null;
            try
            {
                directory = FSDirectory.Open(new DirectoryInfo(segPath), new NativeFSLockFactory());
                //IndexReader:对索引库进行读取的类
                bool indexFileExist = IndexReader.IndexExists(directory); //是否存在索引库文件夹以及索引库特征文件
                if (indexFileExist)
                {
                    //如果索引目录被锁定（比如索引过程中程序异常退出或另一进程在操作索引库），则解锁
                    //Q:存在问题 如果一个用户正在对索引库写操作 此时是上锁的 而另一个用户过来操作时 将锁解开了 于是产生冲突 --解决方法后续
                    if (IndexWriter.IsLocked(directory))
                    {
                        IndexWriter.Unlock(directory);
                    }
                }
                analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
                if (indexFileExist)
                {
                    writer = new IndexWriter(directory, analyzer, false, IndexWriter.MaxFieldLength.UNLIMITED);
                }
                else
                {
                    writer = new IndexWriter(directory, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED);
                }

                writer.MergeFactor = 100;
                writer.SetMaxBufferedDocs(100);
                writer.SetRAMBufferSizeMB(100);
                int a = writer.MergeFactor;
              
                foreach (DataRow dr in dt.Rows)
                {
                    int arcId =Convert.ToInt32( dr["ArchiveID"].ToString());
                    int clsId =Convert.ToInt32(dr["ClassID"].ToString());
                    DataTable dt2 = GetArchiveDetail2(clsId, arcId);
                    string itemId = string.Format("{0}_{1}", clsId, arcId);
                    Lucene.Net.Documents.Document doc = new Lucene.Net.Documents.Document();
                    if (dt2.Rows.Count > 0)
                    {
                        DataRow row = dt2.Rows[0];
                        doc.Add(new Field("itemId", itemId, Field.Store.YES, Field.Index.NOT_ANALYZED));

                        StringBuilder sb = new StringBuilder();
                        if (row["ArchiveName"] != DBNull.Value)
                        {
                            sb.Append(row["ArchiveName"].ToString() + "λ");
                        }
                        if (row["CustomField1"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField1"].ToString() + "λ");
                        }
                        if (row["CustomField2"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField2"].ToString() + "λ");
                        }
                        if (row["CustomField3"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField3"].ToString() + "λ");
                        }
                        if (row["CustomField4"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField4"].ToString() + "λ");
                        }
                        if (row["CustomField5"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField5"].ToString() + "λ");
                        }
                        if (row["CustomField6"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField6"].ToString() + "λ");
                        }
                        if (row["CustomField7"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField7"].ToString() + "λ");
                        }
                        if (row["CustomField8"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField8"].ToString() + "λ");
                        }
                        if (row["CustomField9"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField9"].ToString() + "λ");
                        }
                        if (row["CustomField10"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField10"].ToString() + "λ");
                        }
                        if (row["CustomField11"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField11"].ToString() + "λ");
                        }
                        if (row["CustomField12"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField12"].ToString() + "λ");
                        }
                        if (row["CustomField13"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField13"].ToString() + "λ");
                        }
                        if (row["CustomField14"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField14"].ToString() + "λ");
                        }
                        if (row["CustomField15"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField15"].ToString() + "λ");
                        }
                        if (row["CustomField16"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField16"].ToString() + "λ");
                        }
                        if (row["CustomField17"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField17"].ToString() + "λ");
                        }
                        if (row["CustomField18"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField18"].ToString() + "λ");
                        }
                        if (row["CustomField19"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField19"].ToString() + "λ");
                        }
                        if (row["CustomField20"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField20"].ToString() + "λ");
                        }
                        if (row["CustomField21"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField21"].ToString() + "λ");
                        }
                        if (row["CustomField22"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField22"].ToString() + "λ");
                        }
                        if (row["CustomField23"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField23"].ToString() + "λ");
                        }
                        if (row["CustomField24"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField24"].ToString() + "λ");
                        }
                        if (row["CustomField25"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField25"].ToString() + "λ");
                        }
                        if (row["CustomField26"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField26"].ToString() + "λ");
                        }
                        if (row["CustomField27"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField27"].ToString() + "λ");
                        }
                        if (row["CustomField28"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField28"].ToString() + "λ");
                        }
                        if (row["CustomField29"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField29"].ToString() + "λ");
                        }
                        if (row["CustomField30"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField30"].ToString() + "λ");
                        }
                        if (row["CustomField31"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField31"].ToString() + "λ");
                        }
                        if (row["CustomField32"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField32"].ToString() + "λ");
                        }
                        if (row["CustomField33"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField33"].ToString() + "λ");
                        }
                        if (row["CustomField34"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField34"].ToString() + "λ");
                        }
                        if (row["CustomField35"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField35"].ToString() + "λ");
                        }
                        if (row["CustomField36"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField36"].ToString() + "λ");
                        }
                        if (row["CustomField37"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField37"].ToString() + "λ");
                        }
                        if (row["CustomField38"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField38"].ToString() + "λ");
                        }
                        if (row["CustomField39"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField39"].ToString() + "λ");
                        }
                        if (row["CustomField40"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField40"].ToString() + "λ");
                        }
                        if (row["CustomField41"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField41"].ToString() + "λ");
                        }
                        if (row["CustomField42"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField42"].ToString() + "λ");
                        }
                        if (row["CustomField43"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField43"].ToString() + "λ");
                        }
                        if (row["CustomField44"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField44"].ToString() + "λ");
                        }
                        if (row["CustomField45"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField45"].ToString() + "λ");
                        }
                        if (row["CustomField46"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField46"].ToString() + "λ");
                        }
                        if (row["CustomField47"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField47"].ToString() + "λ");
                        }
                        if (row["CustomField48"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField48"].ToString() + "λ");
                        }
                        if (row["CustomField49"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField49"].ToString() + "λ");
                        }
                        if (row["CustomField50"] != DBNull.Value)
                        {
                            sb.Append(row["CustomField50"].ToString() + "λ");
                        }
                        doc.Add(new Field("SearchField", sb.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));

                        doc.Add(new NumericField("ArchiveId", Field.Store.YES, true).SetIntValue((int)row["ArchiveID"]));
                        doc.Add(new Field("ClassId", clsId.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
                        if (row["ParentID"] != DBNull.Value)
                        {
                            doc.Add(new NumericField("ParentID", Field.Store.YES, true).SetIntValue((int)row["ParentID"]));
                        }
                        if (row["FullVersion"] != DBNull.Value)
                        {
                            doc.Add(new NumericField("FullVersion", Field.Store.YES, true).SetIntValue((int)row["FullVersion"]));
                        }
                        if (row["ShortcutID"] != DBNull.Value)
                        {
                            doc.Add(new NumericField("ShortcutID", Field.Store.YES, true).SetIntValue((int)row["ShortcutID"]));
                        }
                        if (row["ShortcutClassID"] != DBNull.Value)
                        {
                            doc.Add(new NumericField("ShortcutClassID", Field.Store.YES, true).SetIntValue((int)row["ShortcutClassID"]));
                        }
                        doc.Add(new Field("ArchiveName", ConvertObjToStr(row["ArchiveName"]), Field.Store.YES, Field.Index.NOT_ANALYZED));
                        doc.Add(new Field("ArchivePath", ConvertObjToStr(row["ArchivePath"]), Field.Store.YES, Field.Index.NOT_ANALYZED));
                        doc.Add(new Field("ArchiveTypeID", ConvertObjToStr(row["ArchiveTypeID"]), Field.Store.YES, Field.Index.NOT_ANALYZED));
                        doc.Add(new Field("ArchiveGUID", ConvertObjToStr(row["ArchiveGUID"]), Field.Store.YES, Field.Index.NOT_ANALYZED));
                        doc.Add(new Field("ArchiveFlag", ConvertObjToStr(row["ArchiveFlag"]), Field.Store.YES, Field.Index.NOT_ANALYZED));
                        doc.Add(new Field("UploadImage", ConvertObjToStr(row["UploadImage"]), Field.Store.YES, Field.Index.NOT_ANALYZED));

                        if (row["FileSize"] != DBNull.Value)
                        {
                            doc.Add(new NumericField("FileSize", Field.Store.YES, true).SetIntValue((int)row["FileSize"]));
                        }
                        if (row["FileSum"] != DBNull.Value)
                        {
                            doc.Add(new NumericField("FileSum", Field.Store.YES, true).SetLongValue((long)row["FileSum"]));
                        }
                        doc.Add(new Field("FileType", ConvertObjToStr(row["FileType"]), Field.Store.YES, Field.Index.NOT_ANALYZED));
                        doc.Add(new Field("IsVisible", ConvertObjToStr(row["IsVisible"]), Field.Store.YES, Field.Index.NOT_ANALYZED));
                        doc.Add(new Field("IsDelete", ConvertObjToStr(row["IsDelete"]), Field.Store.YES, Field.Index.NOT_ANALYZED));
                        doc.Add(new Field("IsAbandom", ConvertObjToStr(row["IsAbandom"]), Field.Store.YES, Field.Index.NOT_ANALYZED));
                        if (row["PermID"] != DBNull.Value)
                        {
                            doc.Add(new NumericField("PermID", Field.Store.YES, true).SetIntValue((int)row["PermID"]));
                        }
                        doc.Add(new Field("LockUser", ConvertObjToStr(row["LockUser"]), Field.Store.YES, Field.Index.NOT_ANALYZED));
                        if (row["LockTime"] != DBNull.Value)
                        {
                            string t = ((DateTime)row["LockTime"]).ToString("yyyyMMddHHmmss");
                            doc.Add(new Field("LockTime", t, Field.Store.YES, Field.Index.NOT_ANALYZED));
                        }
                        doc.Add(new Field("CreateUser", ConvertObjToStr(row["CreateUser"]), Field.Store.YES, Field.Index.NOT_ANALYZED));
                        if (row["CreateTime"] != DBNull.Value)
                        {
                            string t = ((DateTime)row["CreateTime"]).ToString("yyyyMMddHHmmss");
                            doc.Add(new Field("CreateTime", t, Field.Store.YES, Field.Index.NOT_ANALYZED));
                        }
                        doc.Add(new Field("UpdateUser", ConvertObjToStr(row["UpdateUser"]), Field.Store.YES, Field.Index.NOT_ANALYZED));
                        if (row["UpdateTime"] != DBNull.Value)
                        {
                            string t = ((DateTime)row["UpdateTime"]).ToString("yyyyMMddHHmmss");
                            doc.Add(new Field("UpdateTime", t, Field.Store.YES, Field.Index.NOT_ANALYZED));
                        }
                        if (row["InternalVersion"] != DBNull.Value)
                        {
                            doc.Add(new NumericField("InternalVersion", Field.Store.YES, true).SetIntValue((int)row["InternalVersion"]));
                        }
                        if (row["BorrowCount"] != DBNull.Value)
                        {
                            doc.Add(new NumericField("BorrowCount", Field.Store.YES, true).SetIntValue((int)row["BorrowCount"]));
                        }
                        if (row["TotalCount"] != DBNull.Value)
                        {
                            doc.Add(new NumericField("TotalCount", Field.Store.YES, true).SetIntValue((int)row["TotalCount"]));
                        }
                        if (row["AppraiseNo"] != DBNull.Value)
                        {
                            doc.Add(new NumericField("AppraiseNo", Field.Store.YES, true).SetIntValue((int)row["AppraiseNo"]));
                        }
                        if (row["BrowseNo"] != DBNull.Value)
                        {
                            doc.Add(new NumericField("BrowseNo", Field.Store.YES, true).SetIntValue((int)row["BrowseNo"]));
                        }
                        if (row["DownloadNo"] != DBNull.Value)
                        {
                            doc.Add(new NumericField("DownloadNo", Field.Store.YES, true).SetIntValue((int)row["DownloadNo"]));
                        }
                        doc.Add(new Field("Important", ConvertObjToStr(row["Important"]), Field.Store.YES, Field.Index.NOT_ANALYZED));
                        doc.Add(new Field("Content", ConvertObjToStr(row["Content"]), Field.Store.YES, Field.Index.NOT_ANALYZED));
                        if (row["PermType"] != DBNull.Value)
                        {
                            doc.Add(new NumericField("PermType", Field.Store.YES, true).SetIntValue((int)row["PermType"]));
                        }
                        if (row["ShareType"] != DBNull.Value)
                        {
                            doc.Add(new NumericField("ShareType", Field.Store.YES, true).SetIntValue((short)row["ShareType"]));
                        }
                        if (row["SafetyType"] != DBNull.Value)
                        {
                            doc.Add(new NumericField("SafetyType", Field.Store.YES, true).SetIntValue((short)row["SafetyType"]));
                        }
                        if (row["ProType"] != DBNull.Value)
                        {
                            doc.Add(new NumericField("ProType", Field.Store.YES, true).SetIntValue((short)row["ProType"]));
                        }
                        for (int i = 1; i < 51; i++)
                        {
                            doc.Add(new Field("CustomField" + i, ConvertObjToStr(row["CustomField" + i]), Field.Store.YES, Field.Index.NOT_ANALYZED));
                        }
                        writer.AddDocument(doc);                       
                    }
                    hasDo++;
                    lbHasDo.Text = hasDo.ToString();                    
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                writer.Optimize();
                if (analyzer != null)
                    analyzer.Close();
                if (writer != null)
                    writer.Dispose();
                if (directory != null)
                    directory.Dispose();
            }
        }

        /// <summary>
        /// Object转字符串(主要用来处理数据库字段为空ToString()报错)
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public string ConvertObjToStr(object o)
        {
            if (o == null || string.IsNullOrEmpty(o.ToString())||o==DBNull.Value)
            {
                return "";
            }
            else
            {
                return o.ToString();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Button b = (Button)sender;
            if (b.Text == "暂停")
            {
                b.Text = "继续";
                t.Suspend();
            }
            else
            {
                b.Text = "暂停";
                t.Resume();
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            string segPath = tbIndexPath.Text.Trim();

            FSDirectory directory = null;
            StandardAnalyzer analyzer = null;
            IndexSearcher searcher = null;

            Lucene.Net.Util.Version ver = Lucene.Net.Util.Version.LUCENE_30;
            try
            {
                directory = FSDirectory.Open(new DirectoryInfo(segPath), new NativeFSLockFactory());
                analyzer = new StandardAnalyzer(ver);//StandardAnalyzer只支持英文的空格分词
                searcher = new IndexSearcher(directory, true);
                int s = searcher.MaxDoc;
                tbTotle.Text = s.ToString();

            }
            catch (Exception e2)
            {

            }
        }

        public DataTable GetArchiveDetail2(int clsId, int arcId)
        {
            string sql = string.Format("select p.TypeClass,* from TB_Archive_{0} t inner join TB_ArchiveType p on t.ArchiveTypeID=p.ArchiveTypeID where ArchiveId={1}", clsId, arcId);
            DataTable dt = DBAccess.ExecuteDataTable(sql);
            return dt;
        }
    }
}
